﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml;
using System.ServiceModel.Syndication;

namespace XamlCast.Player.Model {
    public class PodcastFeed {

        public PodcastFeed(string feedUrl) {
            this.Items = new ObservableCollection<PodcastItem>();
            this.LoadFeed(feedUrl);
        }

        public ObservableCollection<PodcastItem> Items { get; private set; }

        private void LoadFeed(string feedUrl) {
            WebClient c = new WebClient();
            c.DownloadStringCompleted += new DownloadStringCompletedEventHandler(c_DownloadStringCompleted);
            c.DownloadStringAsync(new Uri(feedUrl));
        }

        void c_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
            if (!e.Cancelled && e.Error == null) {
                StringReader sr = new StringReader(e.Result);
                XmlReaderSettings setting = new XmlReaderSettings();
                setting.DtdProcessing = DtdProcessing.Parse;
                XmlReader xr = XmlReader.Create(sr, setting);
                SyndicationFeed feed = SyndicationFeed.Load(xr);
                foreach (var f in feed.Items) {
                    var pi = CreatePodcastItem(f);
                    if (pi != null && !this.Items.Contains(pi)) {
                        this.Items.Add(pi);
                    }
                }
            }
        }

        private PodcastItem CreatePodcastItem(SyndicationItem f) {
            var result = new PodcastItem() {
                Title = f.Title.Text,
                Description = f.Summary.Text,
                PublishDate = f.PublishDate.DateTime,
                MediaUrl = GetMediaUrl(f)
            };
            return result;
        }

        private Uri GetMediaUrl(SyndicationItem f) {
            Uri result = null;

            if (f.Links != null && f.Links.Count > 0) {
                foreach (var m in f.Links) {
                    if (!string.IsNullOrEmpty(m.RelationshipType) 
                        && m.RelationshipType.Equals("enclosure", StringComparison.OrdinalIgnoreCase)) {
                        result = m.Uri;
                    }
                }
            }

            return result;
        }

    }
}
